package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.service.BaseMaterialModelService;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.dto.MaterialModelQueryDTO;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.base.table.entity.BaseMaterialModel;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.*;
import com.ray.business.check.*;
import com.ray.business.enums.OrderSendStatusEnum;
import com.ray.business.service.*;
import com.ray.business.table.dto.OrderSendQueryDTO;
import com.ray.business.table.entity.*;
import com.ray.business.table.params.send.OrderSendCreateParams;
import com.ray.business.table.params.send.OrderSendEditParams;
import com.ray.business.table.params.send.OrderSendQueryParams;
import com.ray.business.table.vo.BusinessGoodsVO;
import com.ray.business.table.vo.OrderSendVO;
import com.ray.business.table.vo.SendGoodsVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.common.check.AbstractCheck;
import com.ray.common.dto.PrintDataDTO;
import com.ray.finance.enums.BillSourceEnum;
import com.ray.finance.table.params.bill.BillCreateParams;
import com.ray.magicBlock.BlockDispatch;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.template.TemplateFactory;
import com.ray.template.TemplateRecord;
import com.ray.util.CodeSplitUtil;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.api.StockApi;
import com.ray.wms.builder.GoodsBuilder;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.service.compose.OutService;
import com.ray.wms.table.dto.GoodsDTO;
import com.ray.wms.table.dto.OrderCreateDTO;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.wms.table.params.order.StockQueryParams;
import com.ray.wms.table.vo.order.GoodsVO;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 采购相关接口
 * @Class: OrderSendApi
 * @Package com.ray.business.api
 * @date 2020/6/7 17:52
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class OrderSendApi {

    @Autowired
    private ProdOrderSendService prodOrderSendService;
    @Autowired
    private ProdSendRecordService prodSendRecordService;
    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private OutService outService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProdOrderService prodOrderService;
    @Autowired
    private ProdOrderStepService prodOrderStepService;
    @Autowired
    private ProdBusinessService prodBusinessService;
    @Autowired
    private ProdBusinessInService prodBusinessInService;
    @Autowired
    private BaseMaterialModelService baseMaterialModelService;
    @Autowired
    private ProdOrderGoodsService prodOrderGoodsService;
    @Autowired
    private StockApi stockApi;
    @Autowired
    private BlockDispatch<BillCreateParams, LoginUser, String> createDispatch;
    @Autowired
    private BaseCustomerService baseCustomerService;


    /**
     * 查询采购订单列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<OrderSendVO>> pageOrderSends(CommonPage<OrderSendQueryParams, Page<OrderSendVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();

        CommonPageBuilder<OrderSendQueryDTO, ProdOrderSend> commonPageBuilder = new CommonPageBuilder<>(OrderSendQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdOrderSend> page = prodOrderSendService.page(commonPageBuilder.bulid(), loginUser);
        List<ProdOrderSend> orders = page.getRecords();
        //结果对象
        IPage<OrderSendVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysOrderSend -> {
                OrderSendVO orderVO = new OrderSendVO();
                BeanUtil.copyProperties(sysOrderSend, orderVO);
                //查询仓库信息
                WmsWarehouse wmsWarehouse = wmsWarehouseMap.get(sysOrderSend.getWarehouseCode());
                if (ObjectUtil.isEmpty(wmsWarehouse)) {
                    wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysOrderSend.getWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(wmsWarehouse.getWarehouseCode(), wmsWarehouse);
                }
                orderVO.setWarehouseName(wmsWarehouse.getWarehouseName());
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(sysOrderSend.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    baseCustomer = baseCustomerService.queryCustomerByCustomerCode(sysOrderSend.getCustomerCode(), loginUser);
                    baseCustomerMap.put(sysOrderSend.getCustomerCode(), baseCustomer);
                }
                orderVO.setCustomerName(baseCustomer.getCustomerName());
                return orderVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }


    /**
     * 创建订单
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createOrder(OrderSendCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询订单数据
        ProdOrder prodOrder = prodOrderService.queryOrderByOrderCode(createParams.getOrderNo(), loginUser);
        new OrderCheck(prodOrder).checkNull("订单不存在");
        OrderSendBuilder orderBuilder = new OrderSendBuilder();
        orderBuilder.append(createParams).append(prodOrder).appendStatus(OrderSendStatusEnum.UN_CHECK.getValue()).appendCreate(loginUser);
        //保存商品信息
        List<String> keys = new ArrayList<>();
        //数量
        final List<BigDecimal> quantitys = new ArrayList<>();
        //卷数
        final List<Integer> juanTotal = new ArrayList<>();
        //金额统计
        final List<BigDecimal> total = new ArrayList<>();
        List<ProdSendRecord> records = createParams.getGoods().stream().map(saleGoodsParams -> {
            if (keys.contains(saleGoodsParams.getKey())) {
                throw BusinessExceptionFactory.newException("商品数据重复");
            }
            SendRecordBuilder sendRecordBuilder = new SendRecordBuilder();
            quantitys.add(saleGoodsParams.getQuantity());
            //卷数
            juanTotal.add(saleGoodsParams.getTotal());
            keys.add(saleGoodsParams.getKey());

            //判断是否关联唯一单号
            if (StrUtil.isNotBlank(saleGoodsParams.getCode())) {
                log.info("关联单号:{}", saleGoodsParams.getCode());
                //查询数据信息
                ProdBusinessIn businessIn = prodBusinessInService.getUsableGoodsByCode(saleGoodsParams.getCode(), loginUser);
                new BusinessInCheck(businessIn).checkNull("数据不存在");
                //更新使用状态
                if (!prodBusinessInService.useBusinessIn(saleGoodsParams.getCode(), businessIn.getUpdateVersion(), loginUser)) {
                    log.info("更新记录状态失败:{}", saleGoodsParams.getCode());
                    throw BusinessExceptionFactory.newException("更新记录异常");
                }
                sendRecordBuilder.appendInCode(businessIn.getCode());
                sendRecordBuilder.append(businessIn);
            }
            //查询商品是否存在订单中
            ProdOrderGoods prodOrderGoods = prodOrderGoodsService.queryOrderGoodsByGoodsCode(createParams.getOrderNo(), saleGoodsParams.getGoodsCode(), loginUser);
            new OrderGoodsCheck(prodOrderGoods).checkNull("发货商品不在订单中");
            //计算单个商品总价
            total.add(saleGoodsParams.getQuantity().multiply(NumberUtil.null2Zero(prodOrderGoods.getPrice())));

            sendRecordBuilder.append(saleGoodsParams).appendSendCode(orderBuilder.getCode()).appendOrderNo(createParams.getOrderNo()).
                    appendPrice(prodOrderGoods).appendCreate(loginUser);
            return sendRecordBuilder.bulid();
        }).collect(Collectors.toList());
        orderBuilder.appendQuantity(quantitys.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(total.stream().reduce(BigDecimal::add).get());
        //保存总卷数
        orderBuilder.appenJuanTotal(juanTotal.stream().mapToInt(Integer::intValue).sum());
        //保存订单信息
        if (!prodOrderSendService.save(orderBuilder.bulid())) {
            log.info("保存订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("创建订单异常");
        }
        //保存数据
        prodSendRecordService.saveBatch(records);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 编辑订单
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editOrder(OrderSendEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdOrderSend prodOrderSend = prodOrderSendService.queryOrderSendByOrderSendCode(editParams.getSendCode(), loginUser);
        new OrderSendCheck(prodOrderSend).checkNull("发货单存在").checkCanEdit("发货单不能编辑");
        //查询订单数据
        ProdOrder prodOrder = prodOrderService.queryOrderByOrderCode(prodOrderSend.getOrderNo(), loginUser);
        new OrderCheck(prodOrder).checkNull("订单不存在");
        OrderSendBuilder orderBuilder = new OrderSendBuilder();
        orderBuilder.append(editParams).append(prodOrder).appendEdit(loginUser);
        //还原对应出库的状态
        prodSendRecordService.list(editParams.getSendCode(), loginUser).forEach(prodBusinessOut -> {
            //还原数据
            if (StrUtil.isNotBlank(prodBusinessOut.getInCode())) {
                prodBusinessInService.cancelBusinessIn(prodBusinessOut.getInCode(), loginUser);
            }
        });
        //删除数据
        prodSendRecordService.deleteOrderGoods(editParams.getSendCode(), loginUser);
        //保存商品信息
        List<String> keys = new ArrayList<>();
        //金额统计
        final List<BigDecimal> total = new ArrayList<>();
        //数量
        final List<BigDecimal> quantitys = new ArrayList<>();
        //卷数
        final List<Integer> juanTotal = new ArrayList<>();
        List<ProdSendRecord> records = editParams.getGoods().stream().map(saleGoodsParams -> {
            if (keys.contains(saleGoodsParams.getKey())) {
                throw BusinessExceptionFactory.newException(SysMsgCodeConstant.Error.ERR10000023);
            }
            keys.add(saleGoodsParams.getKey());
            quantitys.add(saleGoodsParams.getQuantity());
            //卷数
            juanTotal.add(saleGoodsParams.getTotal());
            SendRecordBuilder sendRecordBuilder = new SendRecordBuilder();
            //查询数据信息
            ProdBusinessIn businessIn = prodBusinessInService.getUsableGoodsByCode(saleGoodsParams.getCode(), loginUser);
            new BusinessInCheck(businessIn).checkNull("数据不存在");
            //更新使用状态
            if (!prodBusinessInService.useBusinessIn(saleGoodsParams.getCode(), businessIn.getUpdateVersion(), loginUser)) {
                log.info("更新记录失败:{}", saleGoodsParams.getCode());
                throw BusinessExceptionFactory.newException("更新记录异常");
            }
            //查询商品是否存在订单中
            ProdOrderGoods prodOrderGoods = prodOrderGoodsService.queryOrderGoodsByGoodsCode(prodOrderSend.getOrderNo(), saleGoodsParams.getGoodsCode(), loginUser);
            new OrderGoodsCheck(prodOrderGoods).checkNull("发货商品不再定订单中");
            //计算单个商品总价
            total.add(saleGoodsParams.getQuantity().multiply(NumberUtil.null2Zero(prodOrderGoods.getPrice())));

            sendRecordBuilder.appendInCode(businessIn.getCode());
            sendRecordBuilder.append(businessIn);
            sendRecordBuilder.append(saleGoodsParams).appendSendCode(orderBuilder.getCode()).appendOrderNo(prodOrder.getOrderNo())
                    .appendPrice(prodOrderGoods).appendCreate(loginUser).bulid();
            return sendRecordBuilder.bulid();
        }).collect(Collectors.toList());
        orderBuilder.appendQuantity(quantitys.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(total.stream().reduce(BigDecimal::add).get());
        //保存总卷数
        orderBuilder.appenJuanTotal(juanTotal.stream().mapToInt(Integer::intValue).sum());
        //编辑订单信息
        if (!prodOrderSendService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("编辑发货单异常");
        }
        //保存数据
        prodSendRecordService.saveBatch(records);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }


    /**
     * 审核通过
     *
     * @param sendCode
     * @return
     */
    @Transactional
    public Result<String> passOrder(String sendCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdOrderSend prodOrderSend = prodOrderSendService.queryOrderSendByOrderSendCode(sendCode, loginUser);
        new OrderSendCheck(prodOrderSend).checkNull("发货单不存在").checkCanCheck("发货单已经审核");
        OrderSendBuilder orderBuilder = new OrderSendBuilder();
        orderBuilder.appendCode(sendCode).appendStatus(OrderSendStatusEnum.UN_OUT.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodOrderSendService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("发货单审核失败");
        }
        OrderCreateDTO orderCreateDTO = new OrderCreateDTO();
        orderCreateDTO.setBusinessOrderNo(prodOrderSend.getOrderNo());
        orderCreateDTO.setBusinessCode(sendCode);
        orderCreateDTO.setWarehouseCode(prodOrderSend.getWarehouseCode());
        //查询订单商品
        List<ProdSendRecord> records = prodSendRecordService.list(sendCode, loginUser);
        List<GoodsDTO> goodsDTOS = records.stream().map(prodOrderSendRecord -> {
            return new GoodsBuilder().append(prodOrderSendRecord).appendOrderNo(prodOrderSend.getOrderNo()).bulid();
        }).collect(Collectors.toList());
        orderCreateDTO.setGoodsDTOS(goodsDTOS);
        //创建订单
        outService.createOrderOut(orderCreateDTO, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, sendCode);
    }

    /**
     * 删除
     *
     * @param sendCode
     * @return
     */
    @Transactional
    public Result<String> deleteOrder(String sendCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdOrderSend prodOrderSend = prodOrderSendService.queryOrderSendByOrderSendCode(sendCode, loginUser);
        new OrderSendCheck(prodOrderSend).checkNull("发货单不存在").checkCanDelete("发货单不能删除");
        OrderSendBuilder orderBuilder = new OrderSendBuilder();
        orderBuilder.appendCode(sendCode).appendEdit(loginUser).delete();
        //还原对应出库的状态
        prodSendRecordService.list(sendCode, loginUser).forEach(prodBusinessOut -> {
            //还原数据
            if (StrUtil.isNotBlank(prodBusinessOut.getInCode())) {
                prodBusinessInService.cancelBusinessIn(prodBusinessOut.getInCode(), loginUser);
            }
        });
        //编辑订单信息
        if (!prodOrderSendService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("发货单删除失败");
        }
        //删除数据
        prodSendRecordService.deleteOrderGoods(sendCode, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, sendCode);
    }


    /**
     * 取消
     *
     * @param sendCode
     * @return
     */
    @Transactional
    public Result<String> cancelOrder(String sendCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdOrderSend prodOrderSend = prodOrderSendService.queryOrderSendByOrderSendCode(sendCode, loginUser);
        new OrderSendCheck(prodOrderSend).checkNull("发货单不存在").checkCanCancel("发货单不能取消");
        OrderSendBuilder orderBuilder = new OrderSendBuilder();
        orderBuilder.appendCode(sendCode).appendStatus(OrderSendStatusEnum.CANCEL.getValue()).appendEdit(loginUser);
        //还原对应出库的状态
        prodSendRecordService.list(sendCode, loginUser).forEach(prodBusinessOut -> {
            //还原数据
            if (StrUtil.isNotBlank(prodBusinessOut.getInCode())) {
                prodBusinessInService.cancelBusinessIn(prodBusinessOut.getInCode(), loginUser);
            }
        });
        //编辑订单信息
        if (!prodOrderSendService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("发货单取消失败");
        }
        //删除数据
        // prodSendRecordService.deleteOrderGoods(sendCode, loginUser);
        //作废入库订单
        outService.invalidOrderBusinessCode(sendCode, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, sendCode);
    }


    /**
     * 订单详情
     *
     * @param sendCode
     * @return
     */
    public Result<OrderSendVO> viewOrder(String sendCode) {
        LoginUser loginUser = LogInUserUtil.get();
        ProdOrderSend prodOrderSend = prodOrderSendService.queryOrderSendByOrderSendCode(sendCode, loginUser);
        new OrderSendCheck(prodOrderSend).checkNull("发货单不存在");
        OrderSendVO saleVO = new OrderSendVO();
        BeanUtil.copyProperties(prodOrderSend, saleVO);
        //查询仓库信息
        WmsWarehouse wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(prodOrderSend.getWarehouseCode(), loginUser);
        if (ObjectUtil.isNotNull(wmsWarehouse)) {
            saleVO.setWarehouseName(wmsWarehouse.getWarehouseName());
        }
        //查询客信息

        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(prodOrderSend.getCustomerCode(), loginUser);
        if (ObjectUtil.isEmpty(baseCustomer)) {
            saleVO.setCustomerName(baseCustomer.getCustomerName());
        }
        //查询
        List<ProdSendRecord> prodOrderSendRecords = prodSendRecordService.list(sendCode, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();
        Map<String, ProdOrderGoods> goodsMap = new HashMap<>();
        List<SendGoodsVO> saleGoodsVOS = prodOrderSendRecords.stream().map(prodOrderSendRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodOrderSendRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodOrderSendRecord.getGoodsCode(), loginUser);
                modelMap.put(prodOrderSendRecord.getGoodsCode(), materialModelVO);
            }
            ProdOrderGoods orderGoods = goodsMap.get(prodOrderSendRecord.getGoodsCode());
            if (ObjectUtil.isNull(orderGoods)) {
                orderGoods=  prodOrderGoodsService.queryOrderGoodsByGoodsCode(prodOrderSend.getOrderNo(),prodOrderSendRecord.getGoodsCode(),loginUser);
                goodsMap.put(prodOrderSendRecord.getGoodsCode(), orderGoods);
            }
            return new SendGoodsBuilder().append(prodOrderSendRecord).append(materialModelVO).append(orderGoods).bulid();
        }).collect(Collectors.toList());
        saleVO.setGoods(saleGoodsVOS);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, saleVO);
    }


    /**
     * 发货单信息
     *
     * @param sendCode
     * @return
     */
    public Result<List<List<TemplateRecord>>> printData(String sendCode) {
        ValidateUtil.hasLength(sendCode, "参数不能为空");
        LoginUser loginUser = LogInUserUtil.get();
        List<ProdSendRecord> sendRecords = prodSendRecordService.list(sendCode, loginUser);
        //数据转换
        List<List<TemplateRecord>> list = sendRecords.stream().map(sendRecord -> {
            //查询商品信息
            MaterialModelVO materialModelVO = goodsService.queryGoodsByCode(sendRecord.getGoodsCode(), loginUser);
            //查询订单商品信息
            ProdOrderGoods prodOrderGoods = prodOrderGoodsService.queryOrderGoodsByGoodsCode(sendRecord.getOrderNo(), sendRecord.getGoodsCode(), loginUser);
            //打印对象信息
            PrintDataDTO printDataDTO = new PrintDataBuilder().append(materialModelVO).append(sendRecord).append(prodOrderGoods).bulid();
            List<TemplateRecord> records = new TemplateFactory<>().readTemplate(printDataDTO);
            return records;
        }).collect(Collectors.toList());
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, list);
    }


    /**
     * 查询订单可以出库的列表
     *
     * @param businessQueryParams
     * @return
     */
    public Result<List<BusinessGoodsVO>> listOutGoods(OrderSendQueryParams businessQueryParams) {
        Assert.notNull(businessQueryParams, "参数[businessQueryParams]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        List<ProdBusiness> prodBusinesses = new ArrayList<>();

        //查询订单商品
        List<ProdOrderGoods> orderGoods = prodOrderGoodsService.list(businessQueryParams.getOrderNo(), loginUser);
        orderGoods.forEach(orderGoods1 -> {
            //查询订单加工的商品
            ProdOrderStep lastStep = prodOrderStepService.lastStep(CodeSplitUtil.getFirst(orderGoods1.getGoodsCode()), loginUser);
            new AbstractCheck<>(lastStep).checkNull(String.format("%s,工序为配置",orderGoods1.getGoodsCode()));
            //查询订单对应的加工单
            prodBusinesses.addAll(prodBusinessService.listByOrderNoSetpCodeAndGoodsCode(businessQueryParams.getOrderNo(),
                    lastStep.getStepCode(), orderGoods1.getGoodsCode(), loginUser));
        });
        if (ObjectUtil.isNotEmpty(prodBusinesses)) {
            //查询
            List<String> businessCodes = prodBusinesses.stream().map(ProdBusiness::getBusinessCode).collect(Collectors.toList());
            List<BusinessGoodsVO> prodPurchaseRecords = prodBusinessInService.list(businessCodes, loginUser)
                    .stream().map(prodBusinessIn -> {
                        //查询商品详情
                        MaterialModelVO modelVO = goodsService.queryGoodsByCode(prodBusinessIn.getGoodsCode(), loginUser);
                        BusinessGoodsVO businessGoodsVO = new BusinessGoodsVOBuilder()
                                .append(modelVO).append(prodBusinessIn).bulid();
                        return businessGoodsVO;
                    }).collect(Collectors.toList());
            return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, prodPurchaseRecords);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, new ArrayList<>());
    }


    /**
     * 查询订单对应的商品
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<GoodsVO>> listStockGoods(CommonPage<OrderSendQueryParams, Page<MaterialModelVO>> queryParams) {
        Assert.notNull(queryParams, "参数[queryParams]不存在");
        Assert.notNull(queryParams.getEntity(), "参数[entity]不存在");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        OrderSendQueryParams businessQueryParams = queryParams.getEntity();
        //查询订单商品
        List<String> goodsCodes = prodOrderGoodsService.list(businessQueryParams.getOrderNo(), loginUser).stream()
                .map(ProdOrderGoods::getGoodsCode).collect(Collectors.toList());
        //根据类型名称过滤
        MaterialModelQueryDTO materialModelQueryDTO = new MaterialModelQueryDTO();
        BeanUtil.copyProperties(businessQueryParams, materialModelQueryDTO);
        materialModelQueryDTO.setModelCodes(goodsCodes);
        List<String> lastGoodsCodes = baseMaterialModelService.list(materialModelQueryDTO, loginUser).stream().map(BaseMaterialModel::getModelCode).collect(Collectors.toList());
        StockQueryParams stockQueryParams = new StockQueryParams();
        BeanUtil.copyProperties(businessQueryParams, stockQueryParams);
        stockQueryParams.setModelCodes(lastGoodsCodes);
        stockQueryParams.setBusinessOrderNo(queryParams.getEntity().getOrderNo());
        CommonPageBuilder<StockQueryParams, GoodsVO> commonPageBuilder = new CommonPageBuilder<>(StockQueryParams.class);
        commonPageBuilder.appendEntity(stockQueryParams).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        return stockApi.queryStockDetails(commonPageBuilder.bulid());
    }


    /**
     * 完成订单
     *
     * @param prodOrderSend
     * @param loginUser
     * @return
     */
    public Boolean finishOrder(ProdOrderSend prodOrderSend, LoginUser loginUser) {
        List<ProdSendRecord> sendRecords = prodSendRecordService.list(prodOrderSend.getSendCode(), loginUser);
        Map<String, BigDecimal> decimalMap = new HashMap<>();
        //分组求和
        sendRecords.forEach(sendRecord -> {
            //统计完成数量
            BigDecimal quantity = decimalMap.get(sendRecord.getGoodsCode());
            if (ObjectUtil.isNull(quantity)) {
                //处理空异常
                quantity = new BigDecimal(0);
            }
            decimalMap.put(sendRecord.getGoodsCode(), quantity.add(sendRecord.getQuantity()));
        });
        //更新数量
        for (String goodCode : decimalMap.keySet()) {
            ProdOrderGoods orderGoods = prodOrderGoodsService.queryOrderGoodsByGoodsCode(prodOrderSend.getOrderNo(), goodCode, loginUser);
            if (ObjectUtil.isNotNull(orderGoods)) {
                if (!prodOrderGoodsService.updateSendQuantity(prodOrderSend.getOrderNo(), goodCode,
                        NumberUtil.null2Zero(orderGoods.getSendQuantity()).add(decimalMap.get(goodCode)), orderGoods.getUpdateVersion(), loginUser)) {
                    log.info("更新订单发货数量异常");
                    throw BusinessExceptionFactory.newException("更新订单发货数量异常");
                }
            }
        }
        prodOrderSendService.finishOrder(prodOrderSend.getSendCode(), loginUser);
        //完成后生成对账单
        BillCreateParams createParams = new BillCreateParams();
        createParams.setOrderNos(Arrays.asList(prodOrderSend.getSendCode()));
        String billNo = createDispatch.dispatch("createBill", BillSourceEnum.ORDER.getValue(), createParams, loginUser);
        log.info("生成对账单:{}", billNo);
        return true;
    }


    /**
     * 完成订单
     *
     * @param prodOrderSend
     * @param loginUser
     * @return
     */
    public Boolean wmsCancel(ProdOrderSend prodOrderSend, LoginUser loginUser) {
        List<ProdSendRecord> sendRecords = prodSendRecordService.list(prodOrderSend.getSendCode(), loginUser);
        Map<String, BigDecimal> decimalMap = new HashMap<>();
        //分组求和
        sendRecords.forEach(sendRecord -> {
            //统计完成数量
            BigDecimal quantity = decimalMap.get(sendRecord.getGoodsCode());
            if (ObjectUtil.isNull(quantity)) {
                log.info("没有数据，进行初始化");
                quantity = new BigDecimal(0);
            }
            decimalMap.put(sendRecord.getGoodsCode(), quantity.add(sendRecord.getQuantity()));
        });
        //更新数量
        for (String goodCode : decimalMap.keySet()) {
            ProdOrderGoods orderGoods = prodOrderGoodsService.queryOrderGoodsByGoodsCode(prodOrderSend.getOrderNo(), goodCode, loginUser);
            if (ObjectUtil.isNotNull(orderGoods)) {
                if (!prodOrderGoodsService.updateSendQuantity(prodOrderSend.getOrderNo(), goodCode,
                        NumberUtil.null2Zero(orderGoods.getSendQuantity()).subtract(decimalMap.get(goodCode)), orderGoods.getUpdateVersion(), loginUser)) {
                    log.info("更新订单发货数量异常");
                    throw BusinessExceptionFactory.newException("更新订单发货数量异常");
                }
            }
        }
        return true;
    }


}
